<template>
  <div class="monitor-result">
    <a-card title="监控结果">
      <a-form layout="inline" ref="formRefBase">
        <a-form-item label="">
          <a-select
            v-model="queryParam.modelUuid"
            @change="onModelChange"
            placeholder="选择模型"
            :style="{
              width: '210px',
            }"
            default-value=""
          >
            <a-select-option v-for="model in modelList" :key="model.uuid" :value="model.uuid">{{
              model.name
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="">
          <a-select
            v-model="queryParam.version"
            placeholder="选择版本"
            :style="{
              width: '210px',
            }"
          >
            <a-select-option :value="model.version" v-for="model in versionList" :key="model.version">{{
              model.version
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="">
          <a-badge :count="0">
            <a-button icon="filter" style="margin-right: 12px" @click="drawerVisible = true">更多过滤</a-button>
          </a-badge>
          <a-button type="primary" @click="searchHandle">搜索</a-button>
        </a-form-item>
      </a-form>
      <a-drawer
        title="监控结果搜索"
        :visible="drawerVisible"
        @close="onClose"
        width="500px"
        class="monitor-result-drawer"
        :getContainer="$drawerConfig.getContainer"
      >
        <a-form ref="formRef" layout="vertical" hide-required-mark>
          <a-form-item>
            <template slot="label">
              <span>周期类型</span>
              <a-tooltip>
                <template slot="title"> 模型性能指标只支持按天计算 </template>
                <a-icon type="question-circle" class="question-circle" />
              </a-tooltip>
            </template>
            <a-radio-group default-value="D" v-model="queryParam.cycle">
              <a-radio-button value="H"> 小时 </a-radio-button>
              <a-radio-button value="D"> 天 </a-radio-button>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="选择时间">
            <a-range-picker
              :format="queryParam.cycle === 'D' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'"
              :show-time="queryParam.cycle === 'D' ? false : { format: 'HH:mm:ss' }"
              v-model="queryParam.timeRange"
              :style="{
                width: '100%',
              }"
              :value-format="queryParam.cycle === 'D' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss'"
              @change="onTimeRangeChange"
            />
          </a-form-item>
          <a-button type="primary" @click="searchHandle" block style="margin-bottom: 12px">搜索</a-button>
          <a-button @click="resetHandle" block>重置</a-button>
        </a-form>
      </a-drawer>
      <a-tabs v-model="activeKey" @change="handleChange">
        <a-tab-pane tab="变量稳定性" key="1">
          <div v-if="alertConfigField.length">
            <VariableStability
              :alertConfigField="alertConfigField"
              :dataSource="dataSource"
              @variableChange="searchHandle"
            />
          </div>
          <div v-else>
            <Empty />
          </div>
        </a-tab-pane>
        <a-tab-pane tab="变量调用分布" key="2">
          <div v-if="alertConfigField.length">
            <VariableDistribution
              :alertConfigField="alertConfigField"
              :dataSource="dataSource"
              @variableChange="searchHandle"
            />
          </div>
          <div v-else>
            <Empty />
          </div>
        </a-tab-pane>
        <a-tab-pane tab="模型调用量" key="3">
          <div v-if="alertConfigField.length">
            <ModelCall :alertConfigField="alertConfigField" :queryParam="queryParam" :dataSource="dataSource" />
          </div>
          <div v-else>
            <Empty />
          </div>
        </a-tab-pane>
        <a-tab-pane tab="模型性能" key="4">
          <div v-if="alertConfigField.length">
            <ModelPerformance :alertConfigField="alertConfigField" :queryParam="queryParam" :dataSource="dataSource" />
          </div>
          <div v-else>
            <Empty />
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script>
import VariableStability from './components/VariableStability.vue'
import VariableDistribution from './components/VariableDistribution.vue'
import ModelCall from './components/ModelCall.vue'
import ModelPerformance from './components/ModelPerformance.vue'
import Empty from './components/Empty.vue'

import { getAllModel, getAlertConfigField, getMonitorResult, getMonitorEvaluate } from '@/api/monitor'
import moment from 'moment'

export default {
  name: 'MonitorResult',
  components: {
    VariableStability,
    VariableDistribution,
    ModelCall,
    ModelPerformance,
    Empty,
  },
  data() {
    return {
      activeKey: '1',
      modelList: [],
      queryParam: {
        modelUuid: undefined,
        version: undefined,
        cycle: 'D',
        timeRange: [],
        startTime: null,
        endTime: null,
      },
      drawerVisible: false,
      alertConfigField: [],
      dataSource: [],
    }
  },
  computed: {
    versionList() {
      return this.modelList.filter((item) => item.uuid === this.queryParam.modelUuid)
    },
    selectModelData() {
      return this.modelList.find((item) => item.uuid === this.queryParam.modelUuid)
    },
  },
  created() {
    this.initData()
  },
  mounted() {
    this.setDefaultTime()
    const { modelUuid, version } = this.$route.query
    console.log(modelUuid, version, '---------')
    if (modelUuid) {
      this.queryParam.modelUuid = modelUuid
    }
    if (version) {
      this.queryParam.version = version
    }
  },
  methods: {
    initData() {
      getAllModel({ monitor: '1' }).then((res) => {
        if (res.code === 200) {
          this.modelList = res.data
        }
      })
    },
    searchHandle(variables = []) {
      console.log('searchHandle', this.queryParam)
      if (!this.queryParam.modelUuid) {
        this.$message.error('请先选择模型')
        return
      }
      if (this.queryParam.timeRange && this.queryParam.timeRange.length) {
        delete this.queryParam.timeRange
      }
      const typeMap = {
        1: ['PSI'],
        2: ['CALL', 'VARIABLE_CALL'],
        3: ['MODEL_CALL'],
        4: ['EVALUATE'],
      }
      const fieldsList = variables.length ? variables : this.alertConfigField

      const baseParams = {
        ...this.queryParam,
        appName: '',
        fieldsList: JSON.stringify(fieldsList),
        productionCode: '',
        type: typeMap[this.activeKey],
      }
      const params = {
        ...baseParams,
      }
      if (this.activeKey === '2') {
        // fieldsList为单选数组
        params.fieldsList = variables.length
          ? params.fieldsList
          : JSON.stringify(this.alertConfigField.filter((_, index) => index === 0))
      }
      if (this.activeKey === '3') {
        delete params.fieldsList
        params.isBackFlow = false
        params.isDiff = false
        params.labelClassifyVal = 'ALL'
        params.modelType = this.selectModelData.modelType
        params.pageSize = 100
        params.seqId = ''
        params.curPage = 1
        params.total = 0
      }
      this.dataSource = []
      typeMap[this.activeKey].map((item) => {
        params.type = item
        getMonitorResult(params).then((res) => {
          if (res.code === 200) {
            this.dataSource.push(res.data)
            if (this.activeKey === '4') {
              const { uuid, version } = this.selectModelData
              getMonitorEvaluate({ modelUuid: uuid, version }).then((result) => {
                if (result.code === 200) {
                  this.dataSource.push(result.data)
                }
              })
            }
            console.log('res.data', res.data)
          }
        })
      })
    },
    handleChange(key) {
      this.activeKey = key
      this.setDefaultTime()
      this.searchHandle()
    },
    onModelChange(val) {
      const params = {
        modelUuid: val,
        version: this.versionList[0].version,
      }
      this.queryParam = {
        ...this.queryParam,
        ...params,
      }
      getAlertConfigField(params).then((res) => {
        if (res.code === 200) {
          this.alertConfigField = res.data
          this.searchHandle()
        }
      })
    },
    onTimeRangeChange(val) {
      // 当周期类型为天时，确保时间区间为14天
      if (this.queryParam.cycle === 'D' && val && val.length >= 1) {
        let startDate, endDate

        if (val[0] && !val[1]) {
          // 用户只选择了开始时间，结束时间自动设为开始时间后的第14天
          startDate = moment(val[0])
          endDate = moment(val[0]).add(13, 'days') // 加13天是因为包含开始日期，总共14天
          this.queryParam.timeRange = [startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD')]
          // 提示用户
          this.$message.info('当周期类型为天时,时间区间为14天')
        } else if (val[1] && !val[0]) {
          // 用户只选择了结束时间，开始时间自动设为结束时间前的第14天
          endDate = moment(val[1])
          startDate = moment(val[1]).subtract(13, 'days') // 减13天是因为包含结束日期，总共14天
          this.queryParam.timeRange = [startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD')]
          // 提示用户
          this.$message.info('当周期类型为天时,时间区间为14天')
        } else if (val[0] && val[1]) {
          // 用户选择了完整的时间区间，以开始时间为准，调整结束时间为开始时间后的第14天
          startDate = moment(val[0])
          endDate = moment(val[0]).add(13, 'days')
          this.queryParam.timeRange = [startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD')]
          // 提示用户
          this.$message.info('当周期类型为天时,时间区间为14天')
        }
      }

      this.transformDate()
    },
    setDefaultTime() {
      // 当选择模型性能时时间为当前日期减去23天，结束时间为当前日期减去10天
      if (this.activeKey === '4') {
        const endDate = moment().subtract(10, 'days').endOf('day')
        const startDate = moment().subtract(23, 'days').startOf('day')
        this.queryParam.timeRange = [startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD')]
      }
      // 不为模型性能时时间为今天开始结束时间为今天往前14天
      if (this.activeKey !== '4') {
        const endDate = moment().subtract(0, 'day').endOf('day')
        const startDate = moment().subtract(13, 'day').startOf('day')
        this.queryParam.timeRange = [startDate.format('YYYY-MM-DD'), endDate.format('YYYY-MM-DD')]
      }
      console.log('this.queryParam.timeRange', this.queryParam.timeRange)
      this.transformDate()
    },
    transformDate() {
      // 时间转化为时间戳
      if (this.queryParam.timeRange && this.queryParam.timeRange[0]) {
        // 开始时间
        this.queryParam.startTime = moment(this.queryParam.timeRange[0]).unix() * 1000
      }
      if (this.queryParam.timeRange && this.queryParam.timeRange[1]) {
        // 结束时间
        this.queryParam.endTime = moment(this.queryParam.timeRange[1]).unix() * 1000
      }
    },
    onClose() {
      this.drawerVisible = false
    },
    resetHandle() {
      this.queryParam = {}
      this.$refs.formRef.resetFields()
      this.$refs.formRefBase.resetFields()
    },
  },
}
</script>

<style lang="less">
.monitor-result-drawer {
  .question-circle {
    color: @primary-color;
    display: inline-block;
    margin-left: 8px;
    cursor: pointer;
  }
}
</style>
